#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/7/23 18:42
# @Author  : youfeng
import time

from flask import Flask, jsonify, Response

from logger import AppLogger
from proxy_fetcher import ProxyFetcher

log = AppLogger('static_proxy_server.log').get_logger()

app = Flask(__name__)

fetcher = ProxyFetcher("proxies.txt", log)


@app.route('/')
def index():
    return "proxy server is working!"


@app.route("/proxy/num")
def proxy_num():
    return jsonify(fetcher.get_proxy_num())


@app.route("/proxy/list")
def proxy_list():
    # def generate():
    #     for row in fetcher.get_proxy_list():
    #         yield row + "<br/>"

    return Response(fetcher.get_proxy_list_text())


@app.route('/proxy/ip', methods=['GET'])
def get_proxy():
    start_time = time.time()
    proxy = fetcher.get_proxy()
    log.info("当前获取代理: {} 耗时: {} s".format(proxy, time.time() - start_time))
    return proxy


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=9500, threaded=True)
